package com.spaceobj.common.core.utils;

import cn.hutool.http.HttpUtil;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhr_java@163.com
 * @date 2023/5/3 11:05
 */

public class GetIpAddress {

    public static final String url = "https://whois.pconline.com.cn/jsFunction.jsp";

    /**
     * 获取IP属地
     *
     * @param ip IP地址
     *
     * @return IP属地
     */

    public static String getIpTerritory(String ip) {

        String ipTerritory = "中国大陆";

        try {
            if(StringUtils.isEmpty(ip)){
                return ipTerritory;
            }
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("callback", "jsShow");
            paramMap.put("ip", ip);
            // 带参GET请求
            String result2 = HttpUtil.get(url, paramMap);
            int start = result2.indexOf("('") + 2;
            int end = result2.indexOf("',");
            ipTerritory = result2.substring(start, end);
        } catch (Exception e) {
            ExceptionUtil.exceptionToString(e);
            return ipTerritory;
        }
        return ipTerritory;

    }

}
